/**
 * 文章控制器
 * 处理文章相关功能
 */

// 导入数据库连接
const db = require('../config/db');

/**
 * 创建新文章
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 */
const createPostHandler = async (req, res) => {
  try {
    // 解构请求体中的数据
    const {
      title,
      slug,
      content,
      content_markdown,
      excerpt,
      cover_image,
      status = 'draft',
      author_id,
      category_id,
      comment_status = 'open',
      is_top = false,
      is_featured = false,
      is_original = true
    } = req.body;

     // 1. 验证必要字段
    if (!title || !slug || !content || !author_id || !category_id) {
      return res.status(400).json({
        success: false,
        message: '标题、别名、内容、作者ID和分类ID是必填字段'
      });
    }
    
    // 2. 新增：验证分类ID是否存在
    const [categoryRows] = await db.execute('SELECT id FROM categories WHERE id = ?', [category_id]);
    if (categoryRows.length === 0) {
      return res.status(400).json({
        success: false,
        message: `分类ID ${category_id} 不存在，请选择有效的分类`
      });
    }
    
    // 3. 新增：也可以验证作者ID是否存在
    const [authorRows] = await db.execute('SELECT id FROM users WHERE id = ?', [author_id]);
    if (authorRows.length === 0) {
      return res.status(400).json({
        success: false,
        message: `作者ID ${author_id} 不存在，请选择有效的作者`
      });
    }

    // 执行数据库插入操作
    const [result] = await db.execute(
      `INSERT INTO posts ( 
        title, 
        slug, 
        content, 
        content_markdown, 
        excerpt, 
        cover_image, 
        status, 
        author_id, 
        category_id, 
        comment_status, 
        is_top, 
        is_featured, 
        is_original, 
        published_at, 
        created_at, 
        updated_at 
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
      [
        title,
        slug,
        content,
        content_markdown || '',
        excerpt || '',
        cover_image || '',
        status,
        author_id,
        category_id,
        comment_status,
        is_top,
        is_featured,
        is_original,
        status === 'published' ? new Date() : null
      ]
    );

    // 检查是否成功创建文章
    if (result.affectedRows > 0) {
      // 获取新创建的文章信息
      const [posts] = await db.execute('SELECT * FROM posts WHERE id = ?', [result.insertId]);
      const newPost = posts[0];

      res.status(201).json({
        success: true,
        message: '文章创建成功',
        data: newPost
      });
    } else {
      res.status(500).json({
        success: false,
        message: '文章创建失败'
      });
    }
  } catch (error) {
    console.error('创建文章错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

/**
 * 获取文章列表
 * @param {Object} req - Express请求对象，支持分页、排序和筛选
 * @param {Object} res - Express响应对象
 */
const getPostsHandler = async (req, res) => {
  try {
    // 解析查询参数
    const page = parseInt(req.query.page, 10) || 1;
    const limit = parseInt(req.query.limit, 10) || 10;
    const offset = (page - 1) * limit;
    const sort = req.query.sort || 'created_at';
    const order = req.query.order || 'DESC';
    const status = req.query.status;
    const category_id = req.query.category_id;
    const author_id = req.query.author_id;
    const search = req.query.search;

    // 构建查询条件
    let whereConditions = [];
    let queryParams = [];
    
    if (status) {
      whereConditions.push('status = ?');
      queryParams.push(status);
    }
    
    if (category_id) {
      whereConditions.push('category_id = ?');
      queryParams.push(category_id);
    }
    
    if (author_id) {
      whereConditions.push('author_id = ?');
      queryParams.push(author_id);
    }
    
    if (search) {
      whereConditions.push('(title LIKE ? OR content LIKE ? OR excerpt LIKE ?)');
      queryParams.push(`%${search}%`, `%${search}%`, `%${search}%`);
    }

    // 构建完整的SQL查询
    const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : '';
    const baseQuery = `SELECT * FROM posts ${whereClause} ORDER BY ${sort} ${order} LIMIT ? OFFSET ?`;
    const countQuery = `SELECT COUNT(*) as total FROM posts ${whereClause}`;
    
    // 执行查询
    const [posts] = await db.execute(baseQuery, [...queryParams, limit, offset]);
    const [[{ total }]] = await db.execute(countQuery, queryParams);
    
    // 计算总页数
    const totalPages = Math.ceil(total / limit);

    res.status(200).json({
      success: true,
      data: posts,
      pagination: {
        current_page: page,
        total_items: total,
        items_per_page: limit,
        total_pages: totalPages,
        has_next: page < totalPages,
        has_prev: page > 1
      }
    });
  } catch (error) {
    console.error('获取文章列表错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

/**
 * 获取单篇文章详情
 * @param {Object} req - Express请求对象，包含文章ID参数
 * @param {Object} res - Express响应对象
 */
const getPostByIdHandler = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查询文章详情，包括作者和分类信息
    const [posts] = await db.execute(
      `SELECT p.*, u.username as author_name, c.name as category_name 
       FROM posts p 
       LEFT JOIN users u ON p.author_id = u.id 
       LEFT JOIN categories c ON p.category_id = c.id 
       WHERE p.id = ?`,
      [id]
    );
    
    if (posts.length === 0) {
      return res.status(404).json({
        success: false,
        message: '文章不存在'
      });
    }
    
    const post = posts[0];
    
    // 可以在这里添加获取文章标签的逻辑
    // const [tags] = await db.execute('SELECT * FROM tags WHERE id IN (SELECT tag_id FROM post_tags WHERE post_id = ?)', [id]);
    // post.tags = tags;
    
    res.status(200).json({
      success: true,
      data: post
    });
  } catch (error) {
    console.error('获取文章详情错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

/**
 * 更新文章
 * @param {Object} req - Express请求对象，包含文章ID和更新数据
 * @param {Object} res - Express响应对象
 */
const updatePostHandler = async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;
    
    // 首先检查文章是否存在
    const [existingPosts] = await db.execute('SELECT * FROM posts WHERE id = ?', [id]);
    if (existingPosts.length === 0) {
      return res.status(404).json({
        success: false,
        message: '文章不存在'
      });
    }
    
    // 如果更新了分类ID，验证分类是否存在
    if (updateData.category_id) {
      const [categoryRows] = await db.execute('SELECT id FROM categories WHERE id = ?', [updateData.category_id]);
      if (categoryRows.length === 0) {
        return res.status(400).json({
          success: false,
          message: `分类ID ${updateData.category_id} 不存在，请选择有效的分类`
        });
      }
    }
    
    // 如果更新了作者ID，验证作者是否存在
    if (updateData.author_id) {
      const [authorRows] = await db.execute('SELECT id FROM users WHERE id = ?', [updateData.author_id]);
      if (authorRows.length === 0) {
        return res.status(400).json({
          success: false,
          message: `作者ID ${updateData.author_id} 不存在，请选择有效的作者`
        });
      }
    }
    
    // 构建更新字段和参数
    const fields = [];
    const params = [];
    
    // 遍历更新数据，构建SQL字段和参数
    for (const [key, value] of Object.entries(updateData)) {
      // 跳过ID字段，不允许更新ID
      if (key !== 'id' && key !== 'created_at') {
        fields.push(`${key} = ?`);
        // 如果是发布状态改变，更新发布时间
        if (key === 'status' && value === 'published') {
          params.push(new Date());
        } else {
          params.push(value);
        }
      }
    }
    
    // 添加更新时间
    fields.push('updated_at = NOW()');
    
    // 如果没有可更新字段
    if (fields.length === 1) { // 只有updated_at
      return res.status(400).json({
        success: false,
        message: '没有提供有效的更新字段'
      });
    }
    
    // 执行更新
    const sql = `UPDATE posts SET ${fields.join(', ')} WHERE id = ?`;
    const [result] = await db.execute(sql, [...params, id]);
    
    if (result.affectedRows > 0) {
      // 获取更新后的文章信息
      const [updatedPosts] = await db.execute('SELECT * FROM posts WHERE id = ?', [id]);
      
      res.status(200).json({
        success: true,
        message: '文章更新成功',
        data: updatedPosts[0]
      });
    } else {
      res.status(500).json({
        success: false,
        message: '文章更新失败'
      });
    }
  } catch (error) {
    console.error('更新文章错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

/**
 * 删除文章
 * @param {Object} req - Express请求对象，包含文章ID参数
 * @param {Object} res - Express响应对象
 */
const deletePostHandler = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 首先检查文章是否存在
    const [existingPosts] = await db.execute('SELECT * FROM posts WHERE id = ?', [id]);
    if (existingPosts.length === 0) {
      return res.status(404).json({
        success: false,
        message: '文章不存在'
      });
    }
    
    // 执行删除操作
    // 注意：实际项目中可能需要先删除相关的评论、标签关联等
    // const [commentResult] = await db.execute('DELETE FROM comments WHERE post_id = ?', [id]);
    // const [tagResult] = await db.execute('DELETE FROM post_tags WHERE post_id = ?', [id]);
    
    const [result] = await db.execute('DELETE FROM posts WHERE id = ?', [id]);
    
    if (result.affectedRows > 0) {
      res.status(200).json({
        success: true,
        message: '文章删除成功',
        data: { id }
      });
    } else {
      res.status(500).json({
        success: false,
        message: '文章删除失败'
      });
    }
  } catch (error) {
    console.error('删除文章错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      error: error.message
    });
  }
};

module.exports = {
  createPostHandler,
  getPostsHandler,
  getPostByIdHandler,
  updatePostHandler,
  deletePostHandler
};